package com.dmwork.service.customer.controller.front.me;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dmwork.common.base.result.R;
import com.dmwork.common.base.result.ResultCodeEnum;
import com.dmwork.common.base.util.JwtInfo;
import com.dmwork.common.base.util.JwtUtils;
import com.dmwork.common.base.util.MD5;
import com.dmwork.service.base.exception.DmworkException;
import com.dmwork.service.customer.entity.Customer;
import com.dmwork.service.customer.entity.CustomerFollower;
import com.dmwork.service.customer.entity.FollowGroup;
import com.dmwork.service.customer.entity.returnVo.CustomerBriefInfoListVo;
import com.dmwork.service.customer.entity.vo.*;
import com.dmwork.service.customer.feign.InteractionFeignService;
import com.dmwork.service.customer.properties.TokenProperties;
import com.dmwork.service.customer.service.CustomerFollowerService;
import com.dmwork.service.customer.service.CustomerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 李天
 * @since 2021-03-10
 */
@Slf4j
@Api(description = "用户服务，个人业务部分")
@Transactional
@RestController
@RequestMapping("/front/dm_work/customer/me")
public class FrontMeCustomerController {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerFollowerService customerFollowerService;
    @Autowired
    private TokenProperties tokenProperties;

    @ApiOperation("用户注册")
    @PostMapping("register")
    public R register(@ApiParam(value = "注册信息", required = true) @RequestBody RegisterVo registerVo) {
        log.info(registerVo.toString());
        customerService.register(registerVo);
        return R.ok().message("注册成功");
    }

    @ApiOperation("用户登录")
    @PostMapping("login")
    public R login(@ApiParam(value = "用户登录信息", required = true) @RequestBody LoginVo loginVo) throws InterruptedException {
        log.info(loginVo.toString());
        String token = customerService.login(loginVo);
        return R.ok().data("token", token);
    }

    @ApiOperation("解析token获取用户信息")
    @GetMapping("get_tb_info")
    public R getInfo(HttpServletRequest request) {
        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        Customer customer = customerService.getById(jwtInfo.getId());
        TokenCustomerInfo tokenCustomerInfo = new TokenCustomerInfo();
        BeanUtils.copyProperties(customer, tokenCustomerInfo);
//        if (StringUtils.isEmpty(customer.getBackground())) {
//            tokenCustomerInfo.setBackground(customerService.getSpaceDefaultBackgroundUrl());
//        }
        return R.ok().data("item", tokenCustomerInfo);
    }

    @ApiOperation("更新用户信息")
    @PutMapping("update_info")
    public R updateInfo(
            @ApiParam(value = "更新的用户信息", required = true)
            @RequestBody Customer customer) {
        //如果用户头像为空，则赋予其默认头像
        if (customer.getAvatar() == null) {
            customer.setAvatar(Customer.DEFAULT_AVATAR);
        }
        // 检查新更新的用户名、手机号、邮箱号是否已存在
        customerService.checkDupicateInfo(customer);

        customerService.updateById(customer);
        customer = customerService.getById(customer.getId());
        //更新完毕后，重新生成token
        String token = JwtUtils.getJwtToken(new JwtInfo(customer.getId(), customer.getName(), customer.getAvatar(), customer.getSign(), customer.getColor(), customer.getTextColor()), tokenProperties.getExpire()* 24 * 60 * 60);
        return R.ok().message("修改成功").data("token", token);
    }

    @ApiOperation("修改用户密码")
    @PutMapping("update_pwd")
    public R updatePassword(@RequestBody RegisterVo registerVo) {
        Customer customer = new Customer();
        customer.setPassword(MD5.encrypt(registerVo.getPassword()));
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", registerVo.getMobile());
        customerService.update(customer, queryWrapper);
        return R.ok().message("修改成功");
    }

    @ApiOperation("获取个人基本信息")
    @GetMapping("get_base_info")
    public R getBaseInfo(HttpServletRequest request) {
        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        assert jwtInfo != null;
        BaseInfoVo baseInfoVo = customerService.getBaseInfoVoById(jwtInfo.getId());
//        if (StringUtils.isEmpty(baseInfoVo.getBackground())) {
//            baseInfoVo.setBackground(customerService.getSpaceDefaultBackgroundUrl());
//        }
        return R.ok().message("获取成功").data("item", baseInfoVo);
    }

    @ApiOperation("关注指定用户")
    @PutMapping("follow/{customerId}/{followGroupId}")
    public R follow(HttpServletRequest request,
                    @ApiParam(value = "要关注的用户id", required = true) @PathVariable("customerId") String customerId,
                    @ApiParam(value = "关注分组id", required = true) @PathVariable("followGroupId") String followGroupId) {

        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        assert jwtInfo != null;
        customerFollowerService.follow(customerId, jwtInfo.getId(), followGroupId);
        return R.ok().message("关注成功");
    }

    @ApiOperation("取关指定用户")
    @PutMapping("unfollow/{customerId}")
    public R unFollow(HttpServletRequest request,
                      @ApiParam(value = "要关注的用户id", required = true)
                      @PathVariable("customerId") String customerId) {
        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        assert jwtInfo != null;
        customerFollowerService.unFollow(customerId, jwtInfo.getId());
        return R.ok().message("取关成功");
    }

    @ApiOperation("获取关注用户列表")
    @GetMapping("get_follow_list/{followGroupId}/{page}/{limit}")
    public R getFollowList(
            HttpServletRequest request,
            @ApiParam(value = "关注用户分组id", required = true) @PathVariable("followGroupId") String followGroupId,
            @ApiParam(value = "页数", required = true) @PathVariable("page") Integer page,
            @ApiParam(value = "每页记录数", required = true) @PathVariable("limit") Integer limit) {

        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        CustomerBriefInfoListVo customerBriefInfoListVo = customerService.selectFollowList(jwtInfo.getId(), followGroupId, page, limit);
        if (!customerBriefInfoListVo.getBriefInfoVoList().isEmpty()) {
            return R.ok().data("total", customerBriefInfoListVo.getTotal()).data("rows", customerBriefInfoListVo.getBriefInfoVoList());
        } else {
            return R.ok().message("数据为空");
        }
    }


    @ApiOperation("获取粉丝用户列表")
    @GetMapping("get_fans_list/{page}/{limit}")
    public R getFansList(HttpServletRequest request,
                         @ApiParam(value = "页数", required = true) @PathVariable("page") Integer page,
                         @ApiParam(value = "每页记录数", required = true) @PathVariable("limit") Integer limit) {
        JwtInfo jwtInfo = JwtUtils.getCustomerInfoByJwtToken(request);
        CustomerBriefInfoListVo customerBriefInfoListVo = customerService.selectFansList(jwtInfo.getId(), page, limit);
        if (customerBriefInfoListVo != null) {
            return R.ok().data("total", customerBriefInfoListVo.getTotal()).data("rows", customerBriefInfoListVo.getBriefInfoVoList());
        } else {
            return R.ok().message("数据为空");
        }
    }

    @ApiOperation("修改关注用户的分组")
    @PutMapping("modify_follow_group/{customerId}/{followGroupId}")
    public R modifyFollowGroup(
            HttpServletRequest request,
            @ApiParam(value = "要修改关注分组的用户id", required = true) @PathVariable("customerId") String customerId,
            @ApiParam(value = "目标分组id", required = true) @PathVariable("followGroupId") String followGroupId) {

        JwtInfo jwtToken = JwtUtils.getCustomerInfoByJwtToken(request);
        customerFollowerService.updateFollowGroup(customerId, jwtToken.getId(), followGroupId);
        return R.ok().message("修改成功");
    }

    @ApiOperation("修改自定义主题色和字体色")
    @PutMapping("modify_color/{color}/{textColor}")
    public R modify_color(
            HttpServletRequest request,
            @PathVariable String color, @PathVariable String textColor) {

        JwtInfo jwtToken = JwtUtils.getCustomerInfoByJwtToken(request);
        Customer customer = new Customer();
        customer.setId(jwtToken.getId());
        customer.setColor(color);
        customer.setTextColor(textColor);
        customerService.updateById(customer);
        return R.ok().message("修改成功");
    }

}

